package it.trekker.dao.ejb;

import java.util.List;
import it.trekker.dao.IUserDAO;
import it.trekker.dao.User;

import javax.annotation.security.RolesAllowed;
import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;

import org.jboss.security.annotation.SecurityDomain;

@SecurityDomain("TrekkerRealm")
@RolesAllowed("viewer")
@Stateless
@Local(IUserDAO.class)
public class EJB3UserDAO implements IUserDAO {
	
	@PersistenceContext(unitName = "TrekkerUnit")
	protected EntityManager em;

	public int insert(User user) {
		if(user != null) {
			em.persist(user);
			
			return user.getId();
		}
		
		return 0;
	}

	public int remove(int id) {
		User user = findUserById(id);
		
		if(user != null) {
			em.remove(user);
			return id;
		}
		
		return 0;
	}

	public int update(User user) {
		if(user != null) {
			if(em.merge(user) != null)
				return user.getId();
		}
		
		return 0;
	}

	public User findUserById(int id) {
		User result = em.find(User.class, id);
//		result = loadStartPoint(result);
		
		return result;
	}
	
	public User findUserByName(String username) {
		if(username != null) {
			try {
				return (User) em.createQuery("from User u where u.username = :username")
					.setParameter("username", username).getSingleResult();
			} catch (NoResultException e) {
			}
		}
		
		return null;
		
	}

	public List<User> findAllUsers() {
		return em.createQuery("from User").getResultList();
	}
}
